<template>
  <el-drawer
    :visible.sync="drawerVisible"
    :with-header="false"
    :size="showMobilePage?'100%':'80%'"
    :class="{'mobile-resource-drawer':showMobilePage}"
    class="resource-drawer"
    @close="handleClose">
    <div class="drawer-container">
      <div class="head-wrap">
        <Title title="选择账号" font-size="16px" style="margin: 0 0 16px"/>
        <div class="fitter">
          <FilterInput ref="FilterToolRef" v-model="paramsObj" :filter-list="filterList" line-feed show-search-btn @handelClick="queryClick" @queryEmpty="queryEmpty"/>
          <div style="position: absolute;left: 488px;top: 6px;display:flex;" class="mobile-checkbox">
            <el-checkbox v-model="isMine" @change="changeMine">只看我</el-checkbox>
          </div>
          <div style="position: absolute;left: 560px;top: 0px;display:flex;">
            <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
          </div>
        </div>
      </div>
      <u-table
        v-loading="loading"
        v-if="resourceData && resourceData.items.length > 0 || loading"
        ref="tableRef"
        :border="false"
        :row-height="49"
        :height="setTableHeight"
        :data="resourceData.items"
        :row-class-name="tableRowClassName"
        use-virtual
        row-key="mediumId"
        class="fb-table"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        header-cell-class-name="order-data-header-cell"
        fit
        hightlight-current-row
        @sort-change="sortMethod"
        @select="selectTable"
        @select-all="selectTable"
        @selection-change="handleSelectionChange">
        <u-table-column
          align="center"
          type="selection"/>
        <u-table-column :fixed="selectFixed" sortable="custom" prop="resourceName" align="left" label="账号" min-width="140">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.resourceName"/>
          </template>
        </u-table-column>
        <u-table-column sortable="custom" prop="accountId" align="left" label="账号ID" min-width="110">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.resourceId"/>
          </template>
        </u-table-column>
        <u-table-column sortable="custom" prop="platformTypeName" align="left" label="下单平台" min-width="120">
          <template slot-scope="scope">
            <div :class="{'gray-filter': scope.row.status === 0}" class="flex-center resource-name">
              <platformIcon :data="scope.row.platformTypeName" />
              {{ scope.row.platformTypeName || '--' }}
            </div>
          </template>
        </u-table-column>
        <u-table-column sortable="custom" prop="attributionMatrixName" align="left" label="所属经营体" min-width="130">
          <template slot-scope="scope">
            <ToolTip v-if="scope.row.attributionMatrixName" :content="(scope.row.attributionMatrixFullName || scope.row.attributionMatrixName) | getDeptFullName">
              <div class="resource-name ellipsisOne" style="max-width: 120px;">{{ scope.row.attributionMatrixName }}</div>
            </ToolTip>
            <div v-else class="resource-name">--</div>
          </template>
        </u-table-column>
        <!-- 协作部门暂时隐藏 -->
        <u-table-column sortable="custom" prop="cooperationDepartment" align="left" label="协作部门" min-width="130">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.cooperationDepartmentNames"/>
          </template>
        </u-table-column>
        <u-table-column sortable="custom" prop="accountOperationName" align="left" label="所有人员" min-width="130">
          <template slot-scope="scope">
            <el-tooltip
              v-if="scope.row.accountOperationName && scope.row.accountOperationName.length"
              :open-delay="800"
              class="item"
              placement="top"
              effect="dark" >
              <div slot="content" style="max-width: 200px;">{{ scope.row.accountOperationName.join('/') }}</div>
              <div class="resource-name ellipsisOne">{{ scope.row.accountOperationName.join('/') }}</div>
            </el-tooltip>
            <div v-else class="resource-name">--</div>
          </template>
        </u-table-column>
        <u-table-column sortable="custom" prop="operateModeName" align="left" label="运营模式" min-width="160">
          <template slot-scope="scope">
            <div class="resource-name">
              <ToolTip :content="scope.row.operateModeName" />
            </div>
          </template>
        </u-table-column>
        <u-table-column sortable="custom" prop="cooperation" align="left" label="合作运营方" min-width="120">
          <template slot-scope="scope">
            <div class="resource-name">
              <ToolTip :content="scope.row.cooperation" />
            </div>
          </template>
        </u-table-column>
        <u-table-column sortable="custom" prop="validStatus" align="left" label="有效" min-width="80">
          <template slot-scope="scope">
            <div class="resource-name">
              {{ scope.row.status ? '是' : '否' }}
            </div>
          </template>
        </u-table-column>
        <u-table-column align="left" sortable="systemId" prop="systemId" label="系统ID" min-width="100">
          <template slot-scope="scope">
            <div class="resource-name">
              {{ scope.row.systemId || '--' }}
            </div>
          </template>
        </u-table-column>
        <u-table-column align="left" sortable="custom" prop="createName" label="创建人" min-width="100">
          <template slot-scope="scope">
            <div class="resource-name">
              {{ scope.row.createName || '--' }}
            </div>
          </template>
        </u-table-column>
        <u-table-column sortable="custom" prop="createTime" align="left" label="创建时间" min-width="110">
          <template slot-scope="scope">
            <div class="resource-name">
              <span v-if="scope.row.createTime">{{ scope.row.createTime | standardFormat('YYYY/MM/DD') }}</span>
              <span v-else>--</span>
            </div>
          </template>
        </u-table-column>
        <u-table-column sortable="custom" prop="updator" align="left" label="更新人" min-width="90">
          <template slot-scope="scope">
            <div class="resource-name">
              {{ scope.row.updator || '--' }}
            </div>
          </template>
        </u-table-column>
        <u-table-column sortable="custom" prop="updateTime" align="left" label="更新时间" min-width="110">
          <template slot-scope="scope">
            <div class="resource-name">
              <span v-if="scope.row.updateTime">{{ scope.row.updateTime | standardFormat('YYYY/MM/DD') }}</span>
              <span v-else>--</span>
            </div>
          </template>
        </u-table-column>
      </u-table>
      <empty-placeholder v-else style="margin-bottom: 24px" />
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="resourceData.items.length > 0"
          :current-page.sync="page"
          :page-size="perPage"
          :total="resourceData.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          layout="total, prev, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination>
        <div class="center">
          <el-button :disabled="multipleSelectionAll.length === 0" class="ok submit-btn" type="primary" size="small" @click="submit">确定<i v-if="submitLoading" class="el-icon-loading"/></el-button>
          <el-button class="back-btn cancel-btn-style" size="small" @click="handleClose">取消</el-button>
        </div>
        <el-pagination
          v-if="!showMobilePage"
          v-show="resourceData.items.length > 0"
          :current-page.sync="page"
          :page-size="perPage"
          :total="resourceData.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="showMobilePage?'total, prev, pager,jumper':'total, prev, pager, next, sizes, jumper'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </fixed-pagination>
    </div>
  </el-drawer>
</template>
<script>
import { standardFormat } from '@/filters/date';
import { mapState } from 'vuex';
import { getResourceList, getOperateoptions } from '@/api/resource';
import { platformList } from '@/api/select';
import { getDepartmentAll } from '@/api/config';
import { getDeptFullName } from '@/filters/dept';
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
// 组件
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import platformIcon from '@/components/Common/platformIcon';
import mobileTable from '@/mixins/mobileTable';
export default {
  filters: {
    standardFormat, getDeptFullName,
    microTaskFilter(task) {
      if (!task && task !== 0) return '--';
      const taksArr = ['否', '是'];
      return taksArr[task];
    }
  },
  components: {
    EmptyPlaceholder,
    Title,
    platformIcon
  },
  mixins: [tableSelections, TableAdaptive, mobileTable],
  data() {
    return {
      // tableOutsideHeight: 156,
      isUmyTable: true,
      resourceData: {
        items: [],
        total: 0
      },
      tableRefName: 'tableRef', // 表格的ref名称
      idKey: 'mediumId', // 唯一表示字段
      paramsObj: {},
      loading: false,
      submitLoading: false,
      page: 1,
      perPage: 20,
      sortName: '',
      sortType: -1,
      drawerVisible: false,
      deptList: [],
      platformList: [],
      operateModeList: [],
      isMine: false,
      statusOptions: [
        {
          value: 1,
          label: '是'
        },
        {
          value: 0,
          label: '否'
        }
      ]
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'resourceName', name: '账号', labelWidth: '100px', type: 'input' },
        { keyword: 'id', name: '账号ID', labelWidth: '100px', type: 'input' },
        { keyword: 'executor', name: '所有人员', labelWidth: '100px', type: 'input' },
        { keyword: 'operator', name: '合作运营方', labelWidth: '100px', type: 'input' },
        { keyword: 'systemId', name: '系统ID', labelWidth: '100px', type: 'input' },
        { keyword: 'creator', name: '创建人', labelWidth: '100px', type: 'input' },
        { keyword: 'regenerator', name: '更新人', labelWidth: '100px', type: 'input' },
        // 下拉
        { keyword: 'platformId', name: '下单平台', valueName: 'id', labelName: 'value', type: 'select', options: this.platformList },
        { keyword: 'cooperationDepartment', name: '协作部门', type: 'cascaderSelect', childrenVal: 'children', options: this.deptList, labelWidth: '100px' },
        { keyword: 'departmentId', name: '所属经营体', type: 'cascaderSelect', childrenVal: 'children', options: this.deptList, labelWidth: '100px' },
        {
          keyword: 'operateMode', name: '运营模式', valueName: 'value', labelName: 'label',
          childrenVal: 'children', type: 'cascaderSelect', options: this.operateModeList
        },
        { keyword: 'status', name: '是否有效', type: 'select', options: this.statusOptions },
        // 日期
        { keyword: 'createTime', name: '创建时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'updateTime', name: '更新时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' }
      ];
      return arr;
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 230 : 156;
    }
  },
  watch: {
    resourceData: {
      handler: function(val, oldval) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val.items);
        });
      },
      deep: true // 对象内部的属性监听，也叫深度监听
    }
  },
  methods: {
    load() {
      // 获取所属平台
      platformList().then(({ code, data }) => {
        const list = data || '';
        this.platformList = JSON.parse(JSON.stringify(list).replace(/value/g, 'label').replace(/id/g, 'value'));
      });
      getDepartmentAll().then(res => {
        this.deptList = (res && res.data) || [];
      });
      // 获取运营模式
      getOperateoptions().then(res => {
        this.operateModeList = res.data;
      });
    },
    changeMine() {
      this.fetchData();
    },
    openDrawer() {
      this.load();
      this.fetchData(true);
      this.multipleSelectionAll = [];
      this.drawerVisible = true;
      this.submitLoading = false;
    },
    submit() {
      this.submitLoading = true;
      setTimeout(() => {
        this.$emit('getResources', this.multipleSelectionAll);
      }, 0);
      this.drawerVisible = false;
    },
    handleClose() {
      this.drawerVisible = false;
      this.submitLoading = false;
      this.$emit('editSwitch', true);
    },
    // 获取列表
    fetchData(reset = false) {
      if (reset) { this.page = 1; }
      this.loading = true;
      let params = {
        options: encodeURIComponent(JSON.stringify([])),
        platformType: '',
        page: this.page,
        perPage: this.perPage,
        sortType: this.sortType,
        sortName: this.sortName,
        isMine: this.isMine
      };
      params = this.formatParams(params);
      getResourceList(params).then(res => {
        this.loading = false;
        if (res.data.items) {
          res.data.items.forEach((i, index) => {
            if (i.totalOperation && i.totalOperation.length > 0) {
              i.accountOperationName = i.totalOperation.map(j => j.value);
            }
            if (i.cooperationDepartment && i.cooperationDepartment.length > 0) {
              i.cooperationDepartmentNames = i.cooperationDepartment.map(j => j.value).join('/');
            }
          });
        }
        this.resourceData = res.data;
      }).catch(err => {
        this.loading = false;
        console.log(err);
      });
    },
    formatParams(params) {
      const paramsObj = this.paramsObj;
      Object.keys(paramsObj).forEach(key => {
        if (paramsObj[key]) {
          params[key] = paramsObj[key];
        }
      });
      if (paramsObj.status === 0) {
        params.status = paramsObj.status;
      }
      if (paramsObj.createTime && paramsObj.createTime.length === 2) {
        params.createStartTime = paramsObj.createTime[0];
        params.createEndTime = paramsObj.createTime[1] + 86399000;
      }
      if (paramsObj.updateTime && paramsObj.updateTime.length === 2) {
        params.updateStartTime = paramsObj.updateTime[0];
        params.updateEndTime = paramsObj.updateTime[1] + 86399000;
      }
      delete params.createTime;
      delete params.updateTime;
      return params;
    },
    // 排序
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.queryClick();
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.sortName = '';
      this.sortType = -1;
      this.isMine = false;
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    tableRowClassName({ row, rowIndex }) {
      let baseClass = 'pointer';
      if (row.status === 0) {
        baseClass = baseClass + ' invalid-class';
      }
      if (this.multipleSelectionAll && this.multipleSelectionAll.length > 0) {
        const ids = this.multipleSelectionAll.map(i => i[this.idKey]);
        return ids.includes(row[this.idKey]) ? `table-selected ${baseClass}` : baseClass;
      }
      return baseClass;
    },
    handleSelectionChange(e) {
      e.sort(this.compare('$index'));
      this.selectItem = e;
    },
    compare(p) { // 这是比较函数
      return function(m, n) {
        var a = m[p];
        var b = n[p];
        return a - b; // 升序
      };
    }
  }
};
</script>
<style lang="scss" scoped>
	.resource-drawer{
    &::v-deep .el-drawer__body {
      overflow: auto;
    }
		.fb-fixed-pagination{
			position:absolute;
			width: 100% !important;
		}
		.fitter{
			position: relative;
			margin-bottom: 16px;
		}
		.center{
      min-width: 220px;
			display: inline-block;
			margin-left: 20px;
		}
		.drawer-container{
      min-width: 950px;
			padding: 20px 24px 56px;
		}
    .fb-table{
      .invalid-class {
        .cell,.resource-name {
          color: #999 !important;
        }
      }
    }
	}
  .mobile-resource-drawer {
    .drawer-container{
      min-width: 100% !important;
		}
    .mobile-checkbox {
      left: 100px !important;
      top: 46px !important;
    }
    ::v-deep .el-drawer__body {
      overflow: unset !important;
    }
  }
</style>
